#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
技能使用情况分析脚本
分析battle_4v4_result.json中的技能使用情况
"""

import json
from collections import defaultdict, Counter
from typing import Dict, List, Set

def analyze_skill_usage():
    """分析技能使用情况"""
    
    # 读取战斗结果文件
    try:
        with open('battle_4v4_result.json', 'r', encoding='utf-8') as f:
            battle_data = json.load(f)
    except FileNotFoundError:
        print("错误：找不到 battle_4v4_result.json 文件")
        return
    except json.JSONDecodeError:
        print("错误：JSON文件格式错误")
        return
    
    # 统计数据
    skills_used = Counter()  # 实际使用的技能
    skills_available = set()  # 所有可用的技能
    character_skills = defaultdict(set)  # 每个角色拥有的技能
    skill_effects = defaultdict(list)  # 技能效果统计
    
    # 收集所有角色拥有的技能
    all_teams = [battle_data['teams']['player_team'], battle_data['teams']['enemy_team']]
    
    for team in all_teams:
        for character in team:
            char_name = character['name']
            for skill in character.get('skills', []):
                skill_id = skill.get('skill_id')
                skill_name = skill.get('name', '未知技能')
                if skill_id:
                    skills_available.add(skill_id)
                    character_skills[char_name].add(f"{skill_name}({skill_id})")
    
    # 分析战斗回合中使用的技能
    battle_results = battle_data.get('battle_results', [])
    
    for round_data in battle_results:
        if not round_data.get('success', False):
            continue
            
        actions = round_data.get('actions', [])
        for action in actions:
            skill_id = action.get('skill_id')
            character_id = action.get('character_id')
            
            if skill_id:
                skills_used[skill_id] += 1
                
                # 统计技能效果
                effects = action.get('effects', [])
                for effect in effects:
                    effect_type = effect.get('effect_type')
                    value = effect.get('value', 0)
                    is_hit = effect.get('is_hit', False)
                    is_crit = effect.get('is_crit', False)
                    is_dodged = effect.get('is_dodged', False)
                    
                    skill_effects[skill_id].append({
                        'type': effect_type,
                        'value': value,
                        'hit': is_hit,
                        'crit': is_crit,
                        'dodged': is_dodged
                    })
    
    # 输出分析结果
    print("="*60)
    print("技能使用情况分析报告")
    print("="*60)
    
    print(f"\n📊 总体统计:")
    print(f"   • 可用技能总数: {len(skills_available)}")
    print(f"   • 实际使用技能数: {len(skills_used)}")
    print(f"   • 技能使用率: {len(skills_used)/len(skills_available)*100:.1f}%")
    
    # 显示实际使用的技能
    print(f"\n✅ 实际使用的技能 ({len(skills_used)}个):")
    for skill_id, count in skills_used.most_common():
        print(f"   • {skill_id}: 使用 {count} 次")
    
    # 显示未使用的技能
    unused_skills = skills_available - set(skills_used.keys())
    if unused_skills:
        print(f"\n❌ 未使用的技能 ({len(unused_skills)}个):")
        for skill_id in sorted(unused_skills):
            print(f"   • {skill_id}")
    
    # 显示每个角色拥有的技能
    print(f"\n👥 角色技能配置:")
    for char_name, skills in character_skills.items():
        print(f"   • {char_name}: {len(skills)}个技能")
        for skill in sorted(skills):
            print(f"     - {skill}")
    
    # 分析技能效果
    print(f"\n🎯 技能效果分析:")
    for skill_id in sorted(skills_used.keys()):
        effects = skill_effects[skill_id]
        if not effects:
            continue
            
        total_uses = len(effects)
        damage_effects = [e for e in effects if e['type'] == 'damage']
        heal_effects = [e for e in effects if e['type'] == 'heal']
        hits = [e for e in effects if e['hit']]
        crits = [e for e in effects if e['crit']]
        dodges = [e for e in effects if e['dodged']]
        
        print(f"\n   📋 {skill_id}:")
        print(f"      总使用次数: {skills_used[skill_id]}")
        print(f"      总效果次数: {total_uses}")
        
        if damage_effects:
            avg_damage = sum(e['value'] for e in damage_effects) / len(damage_effects)
            max_damage = max(e['value'] for e in damage_effects)
            print(f"      伤害效果: {len(damage_effects)}次, 平均{avg_damage:.1f}, 最高{max_damage}")
        
        if heal_effects:
            avg_heal = sum(e['value'] for e in heal_effects) / len(heal_effects)
            max_heal = max(e['value'] for e in heal_effects)
            print(f"      治疗效果: {len(heal_effects)}次, 平均{avg_heal:.1f}, 最高{max_heal}")
        
        if total_uses > 0:
            hit_rate = len(hits) / total_uses * 100
            crit_rate = len(crits) / total_uses * 100
            dodge_rate = len(dodges) / total_uses * 100
            print(f"      命中率: {hit_rate:.1f}%, 暴击率: {crit_rate:.1f}%, 闪避率: {dodge_rate:.1f}%")
    
    # 检查技能模板文件
    print(f"\n🔍 技能模板检查:")
    try:
        with open('skill_templates.json', 'r', encoding='utf-8') as f:
            skill_templates = json.load(f)
        
        template_skills = set(skill_templates.keys())
        print(f"   • 技能模板文件中定义的技能: {len(template_skills)}个")
        
        # 检查是否有技能在战斗中使用但模板中没有定义
        missing_in_template = set(skills_used.keys()) - template_skills
        if missing_in_template:
            print(f"   ⚠️  在战斗中使用但模板中缺失的技能: {missing_in_template}")
        
        # 检查是否有技能在模板中定义但从未使用
        never_used = template_skills - skills_available
        if never_used:
            print(f"   📝 模板中定义但角色未配置的技能: {len(never_used)}个")
            
    except FileNotFoundError:
        print("   ⚠️  找不到 skill_templates.json 文件")
    except json.JSONDecodeError:
        print("   ⚠️  skill_templates.json 文件格式错误")
    
    print(f"\n" + "="*60)
    print("分析完成")
    print("="*60)

if __name__ == "__main__":
    analyze_skill_usage()